<style scoped>
  .weui-form-preview__hd label, .weui-form-preview__hd em {
    font-size: .9em !important;
  }
  .weui-loadmore_line .weui-loadmore__tips {
    background-color: #eee;
  }
  .rj-cell.max span{
    font-size: 16px;
    padding-right: 20px;
  }
  .rj-cell label {
    color: #333;
    font-size: 14px;
    width: 44%;
    display: inline-block;
    padding: 5px 3%;
    text-align: right;
  }
  .rj-cell span {
    font-size: 14px;
    color: #333;
    display: inline-block;
    width: 50%;
  }
  .rj-cell.note label{
    float: left;
  }
  .rj-cell.note span{
    width: 80%;
    display: inline-block;
  }
  .weui-cells {
    margin-top: 0;
  }
  .weui-cells_form {
    background: #fbfbfb;
  }
  .weui-cell {
    background: #fff;
  }
  #acts span {
    font-size: 14px;
  }
  .halfbtn {
    display: inline-block;
    width: 49%;
  }
  .weui-label{
    /*width: 130px;*/
    text-align: left;
  }

  .weui-select {
    height: auto;
    line-height: normal;
  }
  *{
    list-style:none;
  }
  /*body{*/

  /*}*/
  .weui-cell_select {
    padding: 10px 15px;
  }
  .weui-cells__title {
    text-align: left;
  }
  .hide {
    display: none;
  }
  #acts {
    font-size: 0;
  }
  #acts span {
    font-size: 14px;
  }
  .fixbtn {
    position: absolute;
    right: -10px;
    font-size: 12px;
    bottom: -10px;
    color: #ccc;
    z-index: 1000;
    background: #fff;
    padding: 0 5px;
  }
</style>
<template>
  <div class="sendcar">
    <div style="height: 50px; line-height: 50px; background: #f7f7f7; text-align: center; font-size: 16px; border-bottom: 1px solid #bdbbbc; position: relative">
      录入领料单
      <a href="javascript:;" @click="$router.back(-1)" style="position: absolute; left: 10px; top: 8px">
        <img src="../../assets/back.png" style="width: 20px" />
      </a>
    </div>
    <div class="weui-cells weui-cells_form">
      <form action="" method="post" id="formid">
        <input type="hidden" name="produceplanid" :value="planid" />
        <div class="cellgroup">
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">货品所属</label></div>
            <div class="weui-cell__bd" style="position: relative;">
              <p @click="expendPerm2" class="fixbtn">跨公司领料？</p>
              <input type="hidden" name="orgid" :value="orgid" v-if="!canEditOrg">
              <select class="weui-select" name="orgid" v-model="orgid" :disabled="!canEditOrg">
<!--                <option :value="orgid">{{orgname}}</option>-->
                <option selected=""  v-for="(item, index) in orgs" :key="item.guid" :value="item.guid">{{item.name}}</option>
              </select>
<!--              <input class="weui-input" type="hidden"  name="orgid" :value="produceplans.orgid" />-->
<!--              <input class="weui-input" type="text" readonly  name="" :value="produceplans.orgname" />-->
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">所在班组</label></div>
            <div class="weui-cell__bd">
              <select class="weui-select" name="departmentid">
                <option selected=""  v-for="(item, index) in departments" :key="item.guid" :value="item.guid">{{item.name}}</option>
              </select>
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">领料类别</label></div>
            <div class="weui-cell__bd">
              <select class="weui-select" name="picktype" v-model="picktype">
                <option v-for="(item, index) in picktypes" :value="item.dictkey">{{item.dicttext}}</option>
              </select>
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">库房</label></div>
            <div class="weui-cell__bd" style="position: relative;">
              <p v-if="conditionSR" @click="expendPerm" class="fixbtn">跨库房领料？</p>
              <input type="hidden" name="strmid" :value="strmid" v-if="!canEditRoom">
              <select class="weui-select" name="strmid" v-model="strmid" :disabled="!canEditRoom">
                <option selected=""  v-for="(item, index) in rooms" :key="item.guid" :value="item.guid">{{item.name}}</option>
              </select>
<!--              <input class="weui-input" type="hidden"  name="strmid" :value="produceplans.strmid" />-->
<!--              <input class="weui-input" type="text" readonly  name="" :value="produceplans.strname" />-->
            </div>
          </div>
        </div>
        <PickItem v-for="(item, index) in oitems" :key="index" :itemNo="item" :isLast="index+1 == oitems.length" :products="products" @doAddItem="addItem(index + 1)" @doDelItem="delItem"></PickItem>
        <div class="weui-btn-area">
          <a class="weui-btn weui-btn_primary halfbtn subbtn"  href="javascript:" @click="send">提交</a>
          <a class="weui-btn weui-btn_primary halfbtn"  href="javascript:" @click="$router.back(-1)" id="sub">返回</a>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
  import PickItem from "./PickItem";
  export default {
    name: 'AddPickingList',
    data () {
      return {
        openid: localStorage.openid,
        planid: '',
        produceplans: [],
        products: [],
        departments: [],
        rooms: [],
        orgs: [],
        orgid: '',
        orgname: '',
        strmid: '',
        reset: false,
        canEditRoom: false,
        conditionSR: false,
        canEditOrg: false,
        oitems: [0],
        picktypes: [],
        picktype: ''
      }
    },
    components: {PickItem},
    created() {
      window.addEventListener('setItem', ()=> {
        this.openid = localStorage.getItem('openid');
      })
    },
    mounted () {
      let that = this;
      this.planid = this.$route.query.guid;
      this.conditionSR = this.$route.query.conditionSR == 'true';
      //获取回显数据
      this.getProductplan(this.$route.query.guid);
      //获取公司
      this.getOrgs();
      //获取库房
      this.getRooms();
      //获取部门
      //this.getDepartment();
      //领料类型
      this.getPicktypes();
      //添加明细item
      $('form').on('click', '#addItem', function () {
        $('.oitem:hidden').eq(0).find('input').attr("disabled",false);
        $('.oitem:hidden').eq(0).find('textarea').attr("disabled",false);
        $('.oitem:hidden').eq(0).find('select').attr("disabled",false);
        $('.oitem:hidden').eq(0).show();
        updateActBtns();
      })
      //删除明细
      $('form').on('click', '#delItem', function () {
        var elm = $(this).parents('.oitem');
        $.confirm("确定要删除该货品明细吗？", function () {
          elm.find('input').val('');
          elm.find('textarea').val('');
          elm.hide();
          $('.oitem:hidden').eq(0).find('input').attr("disabled",true);
          $('.oitem:hidden').eq(0).find('textarea').attr("disabled",true);
          $('.oitem:hidden').eq(0).find('select').attr("disabled",true);
          updateActBtns();
        })
      })
      //调整添加、删除按钮位置
      function updateActBtns() {
        $('#acts').remove();
        var actHtml = '<p id="acts" style="float: right;color: #1aad19;"><span id="addItem" style="padding-right: 5px;">添加</span><span>|</span><span id="delItem" style="padding-left: 5px;">删除</span></p>';

        if ($('.oitem:visible').length == 5) {
          actHtml = '<p id="acts" style="float: right;color: #1aad19;"><span id="delItem" style="padding-left: 5px;">删除</span></p>';
        } else if ($('.oitem:visible').length == 1) {
          var actHtml = '<p id="acts" style="float: right;color: #1aad19;"><span id="addItem" style="padding-right: 5px;">添加</span></p>';
        }
        $('.oitem:visible:last').find('.weui-cells__title').append(actHtml);
      }
    },
    watch: {
      'strmid': function () {
        if (!this.reset) return;
        this.getProducts();
      },
      'orgid': function () {
        if (!this.reset) return;
        this.getProducts();
      }
    },
    methods: {
      getPicktypes: function() {
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Sellform!findDict.action',
          params: {type: 26}
        }).then(response => {
          if (response.statusText == "OK") {
            this.picktypes = response.data;
            this.picktype = response.data[0].dictkey;
          } else {
            this.toastText('获取领料类型数据失败');
          }
        });
      },
      addItem: function(index) {
        this.oitems.push(index);
      },
      delItem: function() {
        this.oitems.pop();
      },
      expendPerm: function() {
        this.reset = true;
        this.canEditRoom = true;
      },
      expendPerm2: function() {
        this.reset = true;
        this.canEditOrg = true;
      },
      getDepartment: function() {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Salespermission!getPermisForDepart.action?openid=' + this.openid,
          params: {functionTypes: 3, departype: 2}
        }).then(response => {
          if (response.data.msg == "true") {
            that.departments = response.data.department;
          } else {
            this.toastText('获取部门数据失败');
          }
        });
      },
      getProductplan: function(planid) {
        this.axios({
          method: 'get',
          url: '/produce/Pickinglist!getBaseInfo.action?openid=' + this.openid,
          params: {planid: planid}
        }).then((response) => {
          if (response.data.msg == 'success') {
            let data = response.data;
            this.departments = data.departs;
            this.produceplans = data.plan;
            this.strmid = data.plan.strmid;
            this.orgid = data.plan.orgid;
            this.products = data.products;
          } else if (response.data.msg == 'outlogin') {
            this.toastError('请重新登录');
          } else {
            this.toastError("系统错误");
          }

        })
      },
      getOrgs: function() {
        this.axios({
          method: 'get',
          url: '/produce/Produceplan!getOrgbyWh.action',
          params: {}
        }).then((response) => {
          if (response.data.status == 'true') {
            this.orgs = response.data.result;
            //this.orgid = response.data.result[0].guid;
          } else if(response.data.status == 'false') {
            this.toastError(response.data.result);
          } else {
            this.toastError("系统错误");
          }

        })
      },
      getRooms: function() {
        this.axios({
          method: 'get',
          url: '/produce/Pickinglist!getSrsByPermiss.action?openid=' + this.openid,
          params: {}
        }).then((response) => {
          if (response.data.msg == 'success') {
            this.rooms = response.data.srs;
          } else if(response.data.msg == 'outlogin') {
            this.toastError('请重新登录');
          } else {
            this.toastError("系统错误");
          }

        })
      },
      getProducts: function() {
        this.axios({
          method: 'get',
          url: '/produce/Pickinglist!getProducts.action?openid=' + this.openid,
          params: {planid: this.planid, orgguid: this.orgid, srguid:this.strmid}
        }).then((response) => {
          if (response.data.msg == 'success') {
            let data = response.data;
            this.products = data.products;
          } else if (response.data.msg == 'outlogin') {
            this.toastError('请重新登录');
          } else {
            this.toastError("系统错误");
          }

        })
      },
      send: function() {
        if (!this.checkEmy('weight')) {
          this.toastText('重量有误！');
          return false;
        }
        if (!this.checkEmy('product')) {
          this.toastText('产品有误！');
          return false;
        }
        if (!this.checkProduct()) {
          $.toast('货品明细产品重复！')
          return false;
        }
        //防止重复提交
        $('.subbtn').attr("disabled",true).css("pointer-events","none");

        this.axios({
          method: 'post',
          url: '/produce/Pickinglist!savePickinglist.action?openid=' + this.openid,
          params: this.serialize2Obj($("#formid").serializeArray())
        }).then(response => {
          //恢复提交按钮可点击
          $('.subbtn').attr('disabled', false).css("pointer-events","auto");

          if(response.data.msg == "success"){
            this.toastText('操作成功!');
            this.$router.push({name: 'PickingList', query: {status: 1}});
          }else if (response.data.msg == 'outlogin'){
            this.toastError('请重新登录!');
          }else if (response.data.msg == 'overweight'){
            this.toastError('超出领料重量!');
          }else if (response.data.msg == 'error'){
            this.toastError('系统错误!');
          }
        }).catch(function (error) {
          //恢复提交按钮可点击
          $('.subbtn').attr('disabled', false).css("pointer-events","auto");
          this.toastError('系统错误');
        });;

      },
      //判断明细产品是否重复
      checkProduct: function () {
        let parr1 = [];
        let parr2 = [];
        for (let i=0; i<$('.product').length; i++) {
          parr1.push($('.product').eq(i).val());
          parr2.push($('.product').eq(i).val());
        }
        //json数组去重
        for (var i = 0; i < parr2.length; i++) {
          for (var j =i+1; j <parr2.length; ) {
            if (parr2[i] == parr2[j]) {
              parr2.splice(j, 1);//去除重复的对象；
            }else {
              j++;
            }
          }
        }
        return parr1.length == parr2.length ? true : false;
      }
    }
  }


</script>
